import cv2
import numpy as np
from chinese_font import cv2AddChineseText


def distinguish_face_pic(trainer_file, predicted_path, unknown_pic):
    # 1.创建LBPH人脸识别器
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    # 2.识别器读取训练模型 trainer_file
    recognizer.read(trainer_file)
    # 3.打开预测模型，用于人脸匹配
    with open(predicted_path, 'r') as f:
        predicted_name = f.readlines()
    # print(predicted_name)
    predicted_person = ''
    # 4.打开待识别图片
    img = cv2.imread(unknown_pic)
    if img.shape[0] > 1000 or img.shape[1] > 1000:
        for i in range(2, 6, 2):
            img = cv2.resize(img, (img.shape[1] // i, img.shape[0] // i))
            if img.shape[1] < 1000 and img.shape[0] < 1000:
                break
    if img.shape[0] < 500 and img.shape[1] < 500:
        img = cv2.resize(img, (img.shape[1] * 2, img.shape[1] * 2))
    # 5.图片灰度
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    (h, w) = img.shape[:2]
    # 6.DNN人脸检测
    net = cv2.dnn.readNetFromCaffe("dataset/DNN_model/deploy.prototxt",
                                   "dataset/DNN_model/res10_300x300_ssd_iter_140000_fp16.caffemodel")
    blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), [104, 177, 123], False, False)
    net.setInput(blob)
    detections = net.forward()
    # 7.没有检测到人脸
    # pass
    flag1 = False
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        # 8.人脸检测置信度大于0.7
        if confidence > 0.7:
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype('int')
            # 9.LBPH识别器预测人脸
            predicted_index, conf = recognizer.predict(gray[startY:endY, startX:endX])
            # print(predicted_index, conf)
            # 10.预测结果与预测文件对比
            for j in range(len(predicted_name)):
                if str(predicted_index) == str(predicted_name[j]).split(':')[0]:
                    predicted_person = str(predicted_name[j]).split(':')[1].strip()
                    flag1 = True
                    break
            # 11.没有匹配到已有人脸
            if not flag1:
                return "未知人脸\n"
            # 12.匹配到已有人脸，展示预测结果
            print(predicted_person, type(predicted_index))
            img = cv2AddChineseText(img, predicted_person, (startX + 20, startY + 20), (255, 255, 0), 30)
            cv2.imshow('test', img[startY:endY, startX:endX])
            if cv2.waitKey(0) & 0xFF == ord('q'):
                break
    return predicted_person


# path = "picture/train/赵今麦/赵今麦_3.jpg"
# predicted_file_path = 'dataset/predicted.txt'
# trainer_file_path = "dataset/trainer.yam"
# distinguish_face_pic(trainer_file_path, predicted_file_path, path)
